package net.heartbeat.source;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import net.heartbeat.HeartbeatTransferer;

/**
 * 主动对象：周期性发送心跳
 * 
 * @author Bai Yu
 *
 */
public class HeartbeatSource<HeartbeatType> {
	/**
	 * 创建心跳发送器，周期性发送心跳
	 * 
	 * @param heartbeatMaker
	 *            心跳包的构建策略
	 * @param transferer
	 *            心跳包的传输策略
	 * @param sender
	 *            底层传输的实现
	 * @param period
	 *            发送周期（单位：秒）
	 */
	public HeartbeatSource(HeartbeatMaker<HeartbeatType> maker, HeartbeatTransferer<HeartbeatType> transferer,
			HeartbeatSender sender, long period) {
		this.maker = maker;
		this.transferer = transferer;
		this.sender = sender;
		this.period = period;

		final int THREAD_POOL_SIZE = 1;// 只需调度HeartbeatSenderTask这一个线程，故容量为1
		executor = new ScheduledThreadPoolExecutor(THREAD_POOL_SIZE);
	}

	/**
	 * 发送心跳<br>
	 * 调用后，立刻发送一次心跳，然后按固定周期不断发送
	 */
	public void start() {
		executor.scheduleAtFixedRate(new SendHeartbeat<>(maker, transferer, sender), 0, period, TimeUnit.SECONDS);
	}

	private HeartbeatMaker<HeartbeatType> maker;
	private HeartbeatTransferer<HeartbeatType> transferer;
	private HeartbeatSender sender;
	private long period;

	private ScheduledThreadPoolExecutor executor;
}
